#!/bin/sh /etc/rc.common
# Copyright (C) 2022 ImmortalWrt.org

. /lib/functions/network.sh

START=99
USE_PROCD=1

NAME="msd_lite"
PROG="/usr/bin/$NAME"

CONF="/etc/$NAME/$NAME.conf.sample"
CONFDIR="/var/run/$NAME"

add_interface_tiggers() {
	local enabled network
	config_get_bool enabled "$1" "enabled" "1"
	config_get network "$1" "network"

	[ "$enabled" -eq "0" -o -z "$network" ] || procd_add_reload_interface_trigger "$network"
}

validate_msd_lite_section() {
	uci_load_validate "$NAME" "instance" "$1" "$2" \
		'enabled:bool:0' \
		'address:string' \
		'interface:string' \
		'network:string' \
		'threads:uinteger:0' \
		'bind_to_cpu:bool:0' \
		'drop_slow_clients:bool:0' \
		'precache_size:uinteger:4096' \
		'ring_buffer_size:uinteger:1024' \
		'multicast_recv_buffer_size:uinteger:512' \
		'multicast_recv_timeout:uinteger:2' \
		'rejoin_time:uinteger:0'
}

start_instance() {
	local section="$1"
	local seconds="0"

	[ "$2" -eq "0" ] || { logger -p daemon.err -t "$NAME" "$section Validation failed."; return 1; }
	[ "$enabled" -eq "1" ] || return 1

	if [ -n "$network" ]; then
		while [ "$seconds" -le 10 ]; do
			network_flush_cache
			network_get_device interface "$network"
			if [ -n "$interface" ]; then
				break
			else
				let seconds+=2
				sleep 2
			fi
		done
	fi

	if [ -n "$address" ]; then
		local addr bindlist
		for addr in $address; do
			bindlist="${bindlist:+$bindlist\\n\\t\\t\\t}<bind><address>$addr</address></bind>"
		done
	else
		return 1
	fi

	[ "$bind_to_cpu" = "1" ] && bind_to_cpu="yes" || bind_to_cpu="no"
	[ "$drop_slow_clients" = "1" ] && drop_slow_clients="yes" || drop_slow_clients="no"

	mkdir -p "$CONFDIR"
	sed -e "s,@threadsCountMax@,$threads,g" \
	    -e "s,@fBindToCPU@,$bind_to_cpu,g" \
	    -e "s,@bindList@,$bindlist,g" \
	    -e "s,@ifName@,$interface,g" \
	    -e "s,@fDropSlowClients@,$drop_slow_clients,g" \
	    -e "s,@precache@,$precache_size,g" \
	    -e "s,@ringBufSize@,$ring_buffer_size,g" \
	    -e "s,@rcvBuf@,$multicast_recv_buffer_size,g" \
	    -e "s,@rcvTimeout@,$multicast_recv_timeout,g" \
	    -e "s,@rejoinTime@,$rejoin_time,g" \
		"$CONF" > "$CONFDIR/$section.conf"

	procd_open_instance "$section"
	procd_set_param command "$PROG"
	procd_append_param command -c "$CONFDIR/$section.conf"

	procd_set_param limits core="unlimited"
	procd_set_param limits nofile="1000000 1000000"
	procd_set_param respawn
	procd_set_param stderr 1

	procd_close_instance
}

start_service() {
	config_load "$NAME"

	config_foreach validate_msd_lite_section "instance" start_instance
}

stop_service() {
	rm -rf "$CONFDIR"
}

reload_service() {
	stop
	start
}

service_triggers() {
	procd_add_reload_trigger "$NAME"

	config_load "$NAME"
	config_foreach add_interface_tiggers "instance"
}
